// import {regeneratorRuntime} from "../lib/runtime/runtime.js"

let ajax_time = 0;
export const request = (params) => {
  ajax_time++;
  wx.showLoading({
    title: '加载中...',
    mask: true
  });
  return new Promise((resolve, reject) => {
    wx.request({
      ...params,
      success: (result) => {resolve(result)},
      fail: (err) => {reject(err)},
      complete: (res) =>{
        ajax_time--;
        if(ajax_time===0){
          wx.hideLoading({})
        }
      }
    })
  })

}

/**
 * 不展示loading的请求
 */
export const request_noLoading = (params) => {
  return new Promise((resolve, reject) => {
    wx.request({
      ...params,
      success: (result) => {resolve(result)},
      fail: (err) => {reject(err)},
    })
  })
}
/**
 * 获取图像识别access_token
 */
let imgToken = '';
const getImgToken = async () => {
  const api_key = "7YToK0PSaKoMUXgVXAuF2qyo"
  const secret_key = "B7hna1XZDVE49Yr3WaX16qCPYaqOjfRq"
  const res = await request_noLoading({
    url: 'https://aip.baidubce.com/oauth/2.0/token?',
    data: {grant_type: "client_credentials",client_id: api_key, client_secret: secret_key },
    header: {'content-type': 'application/x-www-form-urlencoded'},
    method: "POST",
  })
  const image_token = res.data.access_token
  wx.setStorageSync('image_token', {time: Date.now(), image_token: image_token})
  imgToken = image_token
}

export const returnImgToken = () => {
  // 获取缓存中token值
  const token = wx.getStorageSync('image_token')
  // token过期时间为一个月
  if(!token){
    getImgToken()
  }else{
    if(Date.now() - token.time > 1000 * 60 * 60 * 24 * 25 ){
      getImgToken()
    }else{
      imgToken = token.image_token
    }
  }
  return imgToken
}

/**
 * 图像识别
 * @param {String} img_file_path
 * @param {String} req_url 
 */
// 图片信息promise同步函数
const getImageInfoSync = (img_file_path) => {
  return new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: img_file_path,
      success: (res) => {resolve(res)},
      fail: (err) => {reject(err)},
      complete: (res) => {}
    })
  })
}
// 图像识别回调函数 promise 同步函数
let result_data = []
export const img_discern = async (img_file_path, req_url) => {
  const img_info = await getImageInfoSync(img_file_path)
  const origin_img_width = img_info.width
  const origin_img_height = img_info.height
  if((origin_img_width * origin_img_height) > (4096 * 4096)){
    wx.showToast({
      title: '图片文件太大哦~', 
      icon: "none",
      duration: 2000,
      mask: "true"
    })
  }else{
    // base64编码图片 不支持gif图片格式
    const base64_data = wx.getFileSystemManager().readFileSync(img_file_path,"base64")
    // 携带token 和 base64图片请求识别结果
    const result = await request({
      url: req_url,
      data: {"image": base64_data, baike_num: 6},
      header: {'content-type': 'application/x-www-form-urlencoded'},
      method: "POST"
    })
    // 返回包含错误码，进行提示，图片格式错误哦~
    if(result.data.error_code){
      console.log(result.data);
      wx.showToast({
        title: '图片格式错误哦~',
        mask: "true",
        icon: 'none',
        duration: 1500
      })
    }else{
      // 构造渲染数据集由使用页面完成
      result_data = result.data.result
      // data.forEach(item => {
      //   result_set.push({name: item.name, score: (item.score * 100).toFixed(2), img_url: item.baike_info.image_url, description: item.baike_info.description})
      // })
      // 获取到才返回**
      return result_data
    }
  }
  return []
}

/**
 * 通用文字识别
 * @param {String} img_file_path
 * @param {String} req_url 
 */
// 获取通用文字识别token
let wordToken = ''
const getWordToken = async () => {
  const api_key = 'KU05dF5vTw9FWIj7yywhdXeG'
  const secret_key = 'DGtoGZop7bRZoIEyQH4KGQ0Ho8c7uNGz'
  const res = await request_noLoading({
    url: 'https://aip.baidubce.com/oauth/2.0/token?',
    data: {grant_type: "client_credentials",client_id: api_key, client_secret: secret_key },
    header: {'content-type': 'application/x-www-form-urlencoded'},
    method: "POST",
  })
  const word_token = res.data.access_token
  wx.setStorageSync('word_token', {time: Date.now(), word_token: word_token})
  wordToken = word_token
}
export const returnWordToken = () => {
  // 获取缓存中token值
  const token = wx.getStorageSync('word_token')
  // token过期时间为一个月
  if(!token){
    getWordToken()
  }else{
    if(Date.now() - token.time > 1000 * 60 * 60 * 24 * 25 ){
      getWordToken()
    }else{
      wordToken = token.word_token
    }
  }
  return wordToken
}

// 文本识别回调函数 promise 同步函数
export const word_discern = async (img_file_path, req_url, id_card_side) => {
  const img_info = await getImageInfoSync(img_file_path)
  const origin_img_width = img_info.width
  const origin_img_height = img_info.height
  if((origin_img_width * origin_img_height) > (4096 * 4096)){
    wx.showToast({
      title: '图片文件太大哦~',
      icon: "none",
      duration: 2000,
      mask: "true"
    })
  }else{
    // base64编码图片 不支持gif图片格式
    const base64_data = wx.getFileSystemManager().readFileSync(img_file_path,"base64")
    // 携带token 和 base64图片请求识别结果
    const result = await request({
      url: req_url,
      // -front：身份证含照片的一面 -back：身份证带国徽的一面， 其它接口不需要传此参数
      data: {"image": base64_data, id_card_side: id_card_side},
      header: {'content-type': 'application/x-www-form-urlencoded'},
      method: "POST"
    })
    // 返回包含错误码，进行提示，图片格式错误哦~
    if(result.data.error_code){
      wx.showToast({
        title: '图片格式错误哦~',
        mask: "true",
        icon: 'none',
        duration: 1500
      })
    }else{
      // 构造渲染数据集由使用页面完成
      result_data = result.data
      return result_data
    }
  }
  // 注意多个函数公用一个结果集
  return []
}
/**
 * 图像增强与特效
 * @param {String} img_file_path
 * @param {String} req_url 
 */
// 获取图像特效与增强token
let color_imgToken = ''
const getColorImgToken = async () => {
  const api_key = 'vcIpOyyON0ysGfZhzoC9OQEE'
  const secret_key = 'CBP73BPQiwum3DElerXKOg9UNFYzxMga'
  const res = await request_noLoading({
    url: 'https://aip.baidubce.com/oauth/2.0/token?',
    data: {grant_type: "client_credentials",client_id: api_key, client_secret: secret_key },
    header: {'content-type': 'application/x-www-form-urlencoded'},
    method: "POST",
  })
  const colorImg_token = res.data.access_token
  wx.setStorageSync('colorImg_token', {time: Date.now(), colorImg_token: colorImg_token})
  color_imgToken = colorImg_token
}
export const returnColorImgToken = () => {
  // 获取缓存中token值
  const token = wx.getStorageSync('colorImg_token')
  // token过期时间为一个月
  if(!token){
    getColorImgToken()
  }else{
    if(Date.now() - token.time > 1000 * 60 * 60 * 24 * 25 ){
      getColorImgToken()
    }else{
      color_imgToken = token.colorImg_token
    }
  }
  return color_imgToken
}
// 图片特效与效果增强回调函数 promise 同步函数
export const img_effect = async (img_file_path, req_url, type, option) => {
  const img_info = await getImageInfoSync(img_file_path)
  const origin_img_width = img_info.width
  const origin_img_height = img_info.height
  if((origin_img_width * origin_img_height) > (4096 * 4096)){
    wx.showToast({
      title: '图片文件太大哦~',
      icon: "none",
      duration: 2000,
      mask: "true"
    })
  }else{
    // base64编码图片 不支持gif图片格式
    const base64_data = wx.getFileSystemManager().readFileSync(img_file_path,"base64")
    // 携带token 和 base64图片请求识别结果
    const result = await request({
      url: req_url,
      data: {"image": base64_data, type, mask_id: 8, option},
      header: {'content-type': 'application/x-www-form-urlencoded'},
      method: "POST"
    })
    console.log(result);
    // 返回包含错误码，进行提示，图片格式错误哦~
    if(result.data.error_code){
      wx.showToast({
        title: '图片格式错误哦~',
        mask: "true",
        icon: 'none',
        duration: 1500
      })
    }else{
      // 构造渲染数据集由使用页面完成
      result_data = result.data
      return result_data
    }
  }
  // 注意多个函数公用一个结果集
  return []
}